<script setup lang="ts">
import { reqRoleDelete, reqRolePermission, reqRoleTree } from "@/api/role/role"
import type {
  PermissionItems,
  RoleAddPremissionParams,
  RoleAddPremissionResponse,
  RoleResponse,
  RoleResult,
} from "@/api/types/role"
import useUserStore from "@/store/modules/user"
import { reactive, ref } from "vue"

// 用户信息
const useStoreUser = useUserStore()
const qeury = defineProps(["RoleList", "current"])
const emit = defineEmits(["hideEdit", "getRolelist"])
// 抽屉显示隐藏
const drawer = ref(false)
// 树形组件实例
const treeRef = ref()
// 树形结构数据
const treeData = ref<PermissionItems[]>([])
// 当前角色信息
const currentRoleInfo = reactive<RoleResult>({})

// 树形结构被选中节点
const defaultProps = ref({
  children: "children",
  label: "PerName",
})
// 被勾选的子节点
const checkedkeys = ref()
// 对话框显示隐藏
const dialogVisible = ref(false)

// 获取全部权限列表
const getTreeList = async () => {
  const result: RoleAddPremissionResponse = await reqRoleTree()
  if (result.code == 200) {
    treeData.value = result.data
  }
}
// 抽屉关闭
const coloseDrawer = () => {
  drawer.value = false
  checkedkeys.value = []
}

// 分配角色显示
const roleTree = async (row: RoleResult) => {
  drawer.value = true
  await getTreeList()
  Object.assign(currentRoleInfo, row)
  if (currentRoleInfo.permissions![0] != undefined) {
    let arr = <string[]>[]
    treeData.value.map((item: any) => {
      if (item.children) {
        item.children.map((item1: any) => {
          if (currentRoleInfo.permissions![0].indexOf(item1._id) !== -1) {
            arr.push(item1._id)
          }
        })
      }
    })
    checkedkeys.value = arr
    
  }
}

// 抽屉关闭事件回掉
const handleClose = () => {
  coloseDrawer()
}
// 角色权限份分配
const save = async () => {
  // 选中节点
  const activeID = treeRef.value.getCheckedKeys()
  // 半选中的节点
  let halfChecked = treeRef.value.getHalfCheckedKeys()
  //   数组合并id
  let permisstionId = activeID.concat(halfChecked)
  //   分配权限参数

  const params: RoleAddPremissionParams = {
    id: currentRoleInfo._id as string,
    permisstionId: permisstionId,
  }
  
  //   分配权限
  const result = await reqRolePermission(params)
  if (result.code == 201) {
    Object.assign(currentRoleInfo, {})
    drawer.value = false
    checkedkeys.value =[]
    emit("getRolelist", qeury.current)
    ElMessage.success(result.msg)
    // 判断是否需改本身职位信息
    if (useStoreUser.role[0] == currentRoleInfo.roleName) {
      dialogVisible.value = true
    }
    return
  }
  ElMessage.error(result.msg)
}
// 对话框关闭事件回掉
const handledialogClose = () => {
  closeDialog()
}

// 对话框关闭确认
const closeDialog = async () => {
  await useStoreUser.uselogOut()
}

// 传递编辑角色信息
const editRole = (row: RoleResult) => {
  emit("hideEdit", row)
}
// 删除角色信息
const confirm = async (id: string) => {
  const result: RoleResponse = await reqRoleDelete(id)
  if (result.code == 201) {
    emit("getRolelist", qeury.current)
    ElMessage.success(result.msg)
    return
  }
  ElMessage.error(result.msg)
}
</script>

<template>
  <div class="tables">
    <!-- 角色列表数据 -->
    <el-table :data="RoleList" border>
      <el-table-column label="#" type="index" align="center"></el-table-column>
      <el-table-column
        label="角色"
        align="center"
        prop="roleName"
        width="120"
      ></el-table-column>
      <el-table-column
        label="描述"
        align="center"
        prop="description"
        width="200"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
      ></el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template #="{ row }">
          <el-button
            v-has="`Role.btn.Edit`"
            type="info"
            @click="roleTree(row)"
            size="small"
            icon="Setting"
          ></el-button>
          <el-button
            v-has="`Role.btn.Allot`"
            type="primary"
            @click="editRole(row)"
            size="small"
            icon="Edit"
          ></el-button>

          <el-popconfirm
            title="确认要删除该角色吗?"
            @confirm="confirm(row._id)"
          >
            <template #reference>
              <el-button
                v-has="`Role.btn.delete`"
                type="danger"
                size="small"
                icon="Delete"
              ></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 抽屉数据 -->
    <el-drawer v-model="drawer" title="分配权限" :before-close="handleClose">
      <template #default>
        <el-tree
          ref="treeRef"
          style="max-width: 600px"
          :data="treeData"
          show-checkbox
          node-key="_id"
          default-expand-all
          :default-checked-keys="checkedkeys"
          :props="defaultProps"
        />
        <!-- :default-checked-keys="TreeChecked" -->
      </template>
      <template #footer>
        <el-button type="default" @click="coloseDrawer">取消</el-button>
        <el-button type="primary" @click="save">确认</el-button>
      </template>
    </el-drawer>

    <el-dialog
      v-model="dialogVisible"
      title="角色信息更新"
      width="500"
      :before-close="handledialogClose"
    >
      <span>重新登陆</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="closeDialog"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped></style>
